/*
 *  Copyright 2004 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.webapp.action.core.mailTemplate;

import com.blandware.atleap.common.Constants;
import com.blandware.atleap.common.parsers.html.HTMLPlainTextExtractor;
import com.blandware.atleap.common.util.ConvertUtil;
import com.blandware.atleap.model.core.MailTemplate;
import com.blandware.atleap.service.core.MailTemplateManager;
import com.blandware.atleap.webapp.action.core.BaseAction;
import com.blandware.atleap.webapp.form.core.MailTemplateForm;
import com.blandware.atleap.webapp.util.core.LocaleUtil;
import com.blandware.atleap.webapp.util.core.MergeUtil;
import com.blandware.atleap.webapp.util.core.WebappConstants;
import com.blandware.atleap.webapp.util.core.WebappUtil;
import org.apache.commons.validator.GenericValidator;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.springframework.orm.ObjectOptimisticLockingFailureException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * <p>Updates mail template
 * </p>
 * <p><a href="UpdateMailTemplateAction.java.html"><i>View Source</i></a></p>
 * <p/>
 *
 * @author Sergey Zubtsovskiy <a href="mailto:sergey.zubtsovskiy@blandware.com">&lt;sergey.zubtsovskiy@blandware.com&gt;</a>
 * @author Andrey Grebnev <a href="mailto:andrey.grebnev@blandware.com">&lt;andrey.grebnev@blandware.com&gt;</a>
 * @version $Revision: 1.17 $ $Date: 2008/04/29 17:48:08 $
 * @struts.action name="mailTemplateForm"
 * path="/core/mailTemplate/update"
 * scope="request"
 * input="inputForward"
 * validate="true"
 * roles="core-mailTemplate-update"
 * @struts.action-forward name="inputForward"
 * path=".core.mailTemplate.updateBody"
 * @struts.action-forward name="viewMailTemplate"
 * path="/core/mailTemplate/view.do"
 * redirect="true"
 * @struts.action-forward name="listMailTemplates"
 * path="/core/mailTemplate/list.do"
 * redirect="true"
 * @struts.action-forward name="callUpdateTemplate"
 * path=".core.mailTemplate.update"
 * @struts.action-forward name="callUpdateMailTemplate"
 * path="/core/mailTemplate/callUpdate.do"
 * redirect="false"
 */
public final class UpdateMailTemplateAction extends BaseAction {
	/**
	 * @param mapping  The ActionMapping used to select this instance
	 * @param form     The optional ActionForm bean for this request (if any)
	 * @param request  The HTTP request we are proceeding
	 * @param response The HTTP response we are creating
	 * @return an ActionForward instance describing where and how
	 *         control should be forwarded, or null if response
	 *         has already been completed
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
	                             HttpServletRequest request, HttpServletResponse response) throws Exception {

        if ( isBackPressed(request) ) {
            // First check, may be session has been invalidated and we need to
            // fill content locales again            
            if (request.getSession().getAttribute(WebappConstants.CONTENT_LOCALES_COLLECTION_KEY) == null) {
                List contentLocales = LocaleUtil.getInstance(servlet.getServletContext()).getEnabledLocales();
                request.getSession().setAttribute(WebappConstants.CONTENT_LOCALES_COLLECTION_KEY, contentLocales);
            }
            return mapping.findForward("callUpdateTemplate");
        }

		if ( isCancelled(request) ) {
            request.removeAttribute(WebappConstants.MAIL_TEMPLATE_MERGED_BODY_KEY);
            return mapping.findForward("listMailTemplates");
		}

		if ( request.getSession().getAttribute(WebappConstants.MAIL_TEMPLATE_SUBMITTED_ACTION_KEY) == null ) {

			request.getSession().setAttribute(WebappConstants.MAIL_TEMPLATE_SUBMITTED_ACTION_KEY, "update");

			MailTemplateForm mailTemplateForm = (MailTemplateForm) form;

			Long mailTemplateId;
			if ( !GenericValidator.isBlankOrNull(mailTemplateForm.getId()) ) {
				mailTemplateId = Long.valueOf(mailTemplateForm.getId());
			} else {
				if ( log.isWarnEnabled() ) {
					log.warn("Missing mail template ID. Returning to list...");
				}
				return mapping.findForward("listMailTemplates");
			}

			request.getSession().setAttribute(WebappConstants.MAIL_TEMPLATE_ID_KEY, mailTemplateId);

			MailTemplateManager mailTemplateManager = (MailTemplateManager) getBean(Constants.MAIL_TEMPLATE_MANAGER_BEAN);
			MailTemplate mailTemplate = mailTemplateManager.retrieveMailTemplate(mailTemplateId);

			if ( mailTemplate == null ) {
				// mail template not found. it might be deleted by someone else
				ActionMessages errors = new ActionMessages();
				errors.add("mailTemplateNotFound", new ActionMessage("core.mailTemplate.errors.notFound"));
				saveErrors(request, errors);
				return mapping.findForward("listMailTemplates");
			}

			// HTML plain text extractor instance
			HTMLPlainTextExtractor extractor = new HTMLPlainTextExtractor();

			Map newBody = new HashMap(mailTemplate.getBody());

			WebappUtil.copyProperties(mailTemplate, mailTemplateForm, request);
            WebappUtil.copyFieldValue(mailTemplate.getFrom(), mailTemplateForm.getFromMap());
            WebappUtil.copyFieldValue(mailTemplate.getSubject(), mailTemplateForm.getSubjectMap());
            WebappUtil.copyFieldValue(mailTemplate.getBody(), mailTemplateForm.getBodyMap());
            WebappUtil.copyFieldValue(mailTemplate.getCharset(), mailTemplateForm.getCharsetMap());

			boolean isPlain = mailTemplate.isPlain();

			Map linkedObjects = new HashMap();
			if ( !isPlain ) {
				// get all refs
				Set refs = new HashSet();
				for ( Iterator i = mailTemplateForm.getBodyMap().values().iterator(); i.hasNext(); ) {
					String body = (String) i.next();
					if ( !GenericValidator.isBlankOrNull(body) ) {
						InputStream bodyIS = new ByteArrayInputStream(ConvertUtil.convertToByteArray(body));
						refs.addAll(extractor.extractAllRefs(bodyIS, Constants.DEFAULT_ENCODING));
					}
				}
				linkedObjects = WebappUtil.mapObjectsToRefs(refs, request.getSession().getServletContext(), request.getContextPath());
			}

			try {
				mailTemplateManager.updateMailTemplate(mailTemplate, linkedObjects);
			} catch ( ObjectOptimisticLockingFailureException e ) {
				// mail template was updated or deleted by another transaction
				ActionMessages errors = new ActionMessages();
				errors.add("updateFailed", new ActionMessage("core.mailTemplate.errors.updateFailed"));
				saveErrors(request, errors);

				// merge text
				Map oldBody = mailTemplateForm.getBodyMap();
				Map mergedBody = new HashMap();
				for ( Iterator i = oldBody.entrySet().iterator(); i.hasNext(); ) {
					Map.Entry entry = (Map.Entry) i.next();
					String locale = (String) entry.getKey();
					String oldValue = (String) entry.getValue();
					String newValue = (String) newBody.get(locale);
					String mergedValue = MergeUtil.mergeText(oldValue, newValue);
					mergedBody.put(locale, mergedValue);
				}

				request.setAttribute(WebappConstants.MAIL_TEMPLATE_MERGED_BODY_KEY, mergedBody);

				return mapping.findForward("callUpdateMailTemplate");
			} finally {
				request.getSession().removeAttribute(WebappConstants.MAIL_TEMPLATE_SUBMITTED_ACTION_KEY);
			}
		}
		return mapping.findForward("listMailTemplates");
	}
}